import json
import os
import pytest
from py.xml import html
from config import RunConfig
import requests
import time
import sys


# 设置用例描述表头
def pytest_html_results_table_header(cells):
    cells.insert(2, html.th('Description'))
    cells.pop()


# 设置用例描述表格
def pytest_html_results_table_row(report, cells):
    try:
        cells.insert(2, html.td(report.description))
    except Exception:
        cells.insert(2, html.td("用例报错了"))
    cells.pop()


@pytest.mark.hookwrapper
def pytest_runtest_makereport(item):
    """
    用于向测试用例中添加用例的开始时间、内部注释，和失败截图等.
    :param item:
    """
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    report.description = description_html(item.function.__doc__)
    # report.description = str(item.function.__doc__)
    extra = getattr(report, 'extra', [])
    page = item.funcargs["page"]
    if report.when == 'call':
        xfail = hasattr(report, 'wasxfail')
        if (report.skipped and xfail) or (report.failed and not xfail):
            case_path = report.nodeid.replace("::", "_") + ".png"
            if "[" in case_path:
                case_name = case_path.split("-")[0] + "].png"
            else:
                case_name = case_path

            capture_screenshots(case_name, page)
            img_path = "image/" + case_name.split("/")[-1]
            if img_path:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;" ' \
                       'onclick="window.open(this.src)" align="right"/></div>' % img_path
                extra.append(pytest_html.extras.html(html))
        report.extra = extra


def description_html(desc):
    """
    将用例中的描述转成HTML对象
    :param desc: 描述
    :return:
    """
    if desc is None:
        return "No case description"
    desc_ = ""
    for i in range(len(desc)):
        if i == 0:
            pass
        elif desc[i] == '\n':
            desc_ = desc_ + ";"
        else:
            desc_ = desc_ + desc[i]

    desc_lines = desc_.split(";")
    desc_html = html.html(
        html.head(
            html.meta(name="Content-Type", value="text/html; charset=latin1")),
        html.body(
            [html.p(line) for line in desc_lines]))
    return desc_html


def capture_screenshots(case_name, page):
    """
    配置用例失败截图路径
    :param case_name: 用例名
    :return:
    """
    global driver
    file_name = case_name.split("/")[-1]
    if RunConfig.NEW_REPORT is None:
        raise NameError('没有初始化测试报告目录')
    else:
        image_dir = os.path.join(RunConfig.NEW_REPORT, "image", file_name)
        page.screenshot(path=image_dir)


def pytest_terminal_summary(terminalreporter, exitstatus, config):
    """
    执行结果统计结果方法
    """
    total = terminalreporter._numcollected
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    error = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    wechat = Enterprise_WeChat_notification(total=total,passed=passed, failed=failed)  # 获取企业微信，暂时不需要看
    print("total:", terminalreporter._numcollected)
    # terminalreporter._sessionstarttime 会话开始时间
    duration = time.time() - terminalreporter._sessionstarttime
    print('total times:', duration, 'seconds')

    # 获取通知状态，若通知状态为True，则开启企业微信通知；否则，则不开启通知
    notice_status=os.path.join(str(RunConfig.notice_status))
    if notice_status == "True":
        wechat.send()  # 企业微信发送消息，暂时不需要看
    else:
        return "未执行企业微信通知方法"

class Enterprise_WeChat_notification():
    """
    向企业微信发送消息通知
    """

    def __init__(self, total,passed, failed):
        #企业微信群机器人地址
        self.url = os.path.join(RunConfig.chatbot_url)
        product_name = os.path.join(RunConfig.product_name)
        project_name = os.path.join(RunConfig.project_name)
        server_address = os.path.join(RunConfig.server_address)
        report_absolute_path = os.listdir(os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + os.path.sep + ".") + os.sep + "report")[-1]

        self.header = {'Content-Type': 'application/json'}
        message=("# {}UI自动化测试\n" +
                 "### 共执行<font color=\"comment\">{}条</font>用例，请相关同学注意：\n" +
                 ">通过 <font color=\"info\">{}条</font>用例\n" +
                 ">失败 <font color=\"warning\">{}条</font>用例\n" +
                 "报告地址：[{}/{}/report/{}/report.html]({}/{}/report/{}/report.html)").format(product_name,total,passed,failed,server_address,project_name,report_absolute_path,server_address,project_name,report_absolute_path)

        self.payload = {
            "msgtype": "markdown",
            "markdown": {
                "content": message,
            }
         }

    def send(self):
        requests.post(url=self.url, headers=self.header, data=json.dumps(self.payload))

